<script setup>
import seckillGoodsApi from '@/api/seckill/seckillGoods_api.js'
import seckillActivityApi from '@/api/seckill/seckillActivity_api.js'
import goodsApi from '@/api/goods_api.js'
import { ref, onMounted } from "vue"
import { ElMessageBox, ElMessage } from "element-plus"
import lodash from 'lodash'

//定义绑定的数据
//表格中的数据
const tableData = ref([]);
const total = ref(0);
//定义对话框的显示状态
const editWinVisible = ref(false);
const addWinVisible = ref(false);

// 商品信息缓存
const goodsInfoMap = ref(new Map());
// 活动信息缓存
const activityInfoMap = ref(new Map());
// 商品列表用于下拉选择
const goodsList = ref([]);

//查询数据
const searchObj = ref({
  current: 1,
  limit: 10,
  activity_name: '', // 活动名称查询条件
  goods_name: '', // 商品名称查询条件
  seckill_price: '',
  origin: '',
  stock: '',
  status: '',
});

// 实际传给后端的查询参数
const backendSearchParams = ref({
  current: 1,
  limit: 10,
  activity_id: '', // 实际传给后端的活动ID
  goods_id: '', // 实际传给后端的商品ID
  seckill_price: '',
  origin: '',
  stock: '',
  status: '',
});

//要修改或者新增的数据
const obj = ref({});

const search = async () => {
  try {
    // 更新实际传给后端的参数
    backendSearchParams.value.current = searchObj.value.current;
    backendSearchParams.value.limit = searchObj.value.limit;
    backendSearchParams.value.seckill_price = searchObj.value.seckill_price;
    backendSearchParams.value.origin = searchObj.value.origin;
    backendSearchParams.value.stock = searchObj.value.stock;
    backendSearchParams.value.status = searchObj.value.status;

    console.log('发送的查询参数:', backendSearchParams.value);
    var result = await seckillGoodsApi.getSeckillGoodsPage(
        backendSearchParams.value.current,
        backendSearchParams.value.limit,
        backendSearchParams.value
    );
    console.log('收到的响应数据:', result);

    // 检查返回的数据是否为HTML（表示路径错误）
    if (result && typeof result === 'string' && result.includes('<!DOCTYPE html>')) {
      ElMessage.error('API路径错误，请检查后端服务是否正常运行');
      tableData.value = [];
      total.value = 0;
      return;
    }

    // 检查返回的数据结构
    if (result && typeof result === 'object') {
      // 如果返回的是直接的分页数据
      if (result.records && Array.isArray(result.records)) {
        tableData.value = result.records;
        total.value = result.total || 0;

        // 获取商品信息和活动信息
        await fetchRelatedInfo(result.records);
      }
      // 如果返回的是包含data字段的对象（Result包装）
      else if (result.data && result.data.records && Array.isArray(result.data.records)) {
        tableData.value = result.data.records;
        total.value = result.data.total || 0;

        // 获取商品信息和活动信息
        await fetchRelatedInfo(result.data.records);
      }
      // 其他情况
      else {
        tableData.value = [];
        total.value = 0;
      }
    } else {
      tableData.value = [];
      total.value = 0;
    }
  } catch (error) {
    console.error('获取秒杀商品列表时出错:', error);
    if (error.response) {
      // 服务器响应了错误状态码
      if (error.response.status === 404) {
        ElMessage.error('API接口未找到，请检查后端服务是否正常运行且API路径配置正确');
      } else if (error.response.status === 500) {
        ElMessage.error('服务器内部错误，请联系管理员');
      } else {
        ElMessage.error(`请求失败: ${error.response.status} ${error.response.statusText}`);
      }
    } else if (error.request) {
      // 请求已发出但没有收到响应
      ElMessage.error('无法连接到服务器，请检查网络连接和后端服务是否运行');
    } else {
      // 其他错误
      ElMessage.error('请求失败: ' + error.message);
    }
    tableData.value = [];
    total.value = 0;
  }
}

// 获取相关商品信息和活动信息
const fetchRelatedInfo = async (seckillGoodsList) => {
  try {
    // 为每个商品ID获取商品信息
    for (const item of seckillGoodsList) {
      // 获取商品信息
      if (item.goods_id) {
        await getGoodsInfo(item.goods_id);
      }

      // 获取活动信息
      if (item.activity_id) {
        await getActivityInfo(item.activity_id);
      }
    }
  } catch (error) {
    console.error('获取关联信息时出错:', error);
  }
}

// 获取商品信息 (模仿orderAddr的getGoodsInfo)
const getGoodsInfo = async (goodsId) => {
  if (!goodsInfoMap.value.has(goodsId)) {
    try {
      const goodsInfo = await goodsApi.getGoodsById(goodsId);
      if (goodsInfo && goodsInfo.data) {
        goodsInfoMap.value.set(goodsId, goodsInfo.data);
      } else if (goodsInfo && typeof goodsInfo === 'object') {
        goodsInfoMap.value.set(goodsId, goodsInfo);
      }
    } catch (error) {
      console.error(`获取商品${goodsId}信息失败:`, error);
    }
  }
}

// 获取活动信息 (模仿orderAddr的getUserInfo)
const getActivityInfo = async (activityId) => {
  if (!activityInfoMap.value.has(activityId)) {
    try {
      const activityInfo = await seckillActivityApi.getActivityById(activityId);
      if (activityInfo && activityInfo.data) {
        activityInfoMap.value.set(activityId, activityInfo.data);
      } else if (activityInfo && typeof activityInfo === 'object') {
        activityInfoMap.value.set(activityId, activityInfo);
      }
    } catch (error) {
      console.error(`获取活动${activityId}信息失败:`, error);
    }
  }
}

// 获取商品列表用于下拉选择
const fetchGoodsList = async () => {
  try {
    const result = await goodsApi.getGoodsPage(1, 1000, {});
    if (result && result.records) {
      goodsList.value = result.records;
    }
  } catch (error) {
    console.error('获取商品列表失败:', error);
    ElMessage.error("获取商品列表失败");
  }
}

//页面加载后要挂载的数据
onMounted(async () => {
  await search();
  await fetchGoodsList();
});

//重置查询条件
const resetSearch = () => {
  searchObj.value.activity_name = '';
  searchObj.value.goods_name = '';
  searchObj.value.seckill_price = '';
  searchObj.value.origin = '';
  searchObj.value.stock = '';
  searchObj.value.status = '';
  searchObj.value.current = 1;
  backendSearchParams.value.activity_id = '';
  backendSearchParams.value.goods_id = '';
  backendSearchParams.value.seckill_price = '';
  backendSearchParams.value.origin = '';
  backendSearchParams.value.stock = '';
  backendSearchParams.value.status = '';
  search();
}

//上传成功
const handleUploadSuccess = (response, file) => {
  console.log("-----------------");
  console.log(response);
  console.log(file);
  obj.value.image = response.data;
}

//分页查询用
const handleSizeChange = () => {
  search();
}

//分页查询用
const handleCurrentChange = () => {
  search();
}

//定义方法
const handlerSearch = async () => {
  searchObj.value.current = 1;

  // 根据活动名称查找活动ID
  if (searchObj.value.activity_name) {
    try {
      // 通过活动名称查找活动信息
      const activityResult = await seckillActivityApi.getActivityPage(1, 1000, {name: searchObj.value.activity_name});
      if (activityResult && activityResult.records && Array.isArray(activityResult.records) && activityResult.records.length > 0) {
        // 找到匹配的活动，使用第一个匹配活动的ID
        backendSearchParams.value.activity_id = activityResult.records[0].id;
        console.log('活动', backendSearchParams.value.activity_id);
      } else {
        // 没有找到匹配的活动，设置一个不可能存在的活动ID
        backendSearchParams.value.activity_id = -1;
        console.log('活动1', backendSearchParams.value.activity_id);
      }
    } catch (error) {
      console.error('查询活动信息失败:', error);
      ElMessage.error("查询活动信息失败");
      return; // 出错时直接返回
    }
  } else {
    backendSearchParams.value.activity_id = '';
    console.log('活动2', backendSearchParams.value.activity_id);
  }

  // 根据商品名称查找商品ID
  if (searchObj.value.goods_name) {
    try {
      // 通过商品名称查找商品信息（这里后端支持模糊查询）
      const goodsResult = await goodsApi.getGoodsPage(1, 1000, {name: searchObj.value.goods_name});
      console.log('商品查询结果:', goodsResult);

      if (goodsResult && goodsResult.records && Array.isArray(goodsResult.records) && goodsResult.records.length > 0) {
        // 检查是否有完全匹配的商品名称
        const matchedGoods = goodsResult.records.filter(goods =>
            goods.name && goods.name === searchObj.value.goods_name);

        if (matchedGoods.length > 0) {
          // 使用第一个完全匹配的商品ID
          backendSearchParams.value.goods_id = matchedGoods[0].id;
          console.log('商品', backendSearchParams.value.goods_id);
        } else {
          // 没有找到完全匹配的商品
          // 设置一个不可能存在的商品ID，确保查询结果为空
          backendSearchParams.value.goods_id = -1;
          console.log('商品1', backendSearchParams.value.goods_id);
        }
      } else {
        // 没有找到任何商品
        // 设置一个不可能存在的商品ID，确保查询结果为空
        backendSearchParams.value.goods_id = -1;
        console.log('商品2', backendSearchParams.value.goods_id);
      }
    } catch (error) {
      console.error('查询商品信息失败:', error);
      ElMessage.error("查询商品信息失败");
      // 出错时设置一个不可能存在的商品ID
      backendSearchParams.value.goods_id = -1;
      return; // 出错时直接返回
    }
  } else {
    backendSearchParams.value.goods_id = '';
    console.log('商品3', backendSearchParams.value.goods_id);
  }

  search(); // 执行查询
}

const handlerAdd = () => {//添加
  obj.value = {};
  addWinVisible.value = true;//打开对话框
}

//新增对话框的取消按钮点击事件
const addCancel = () => {
  obj.value = {};//清空数据
  addWinVisible.value = false;//关闭新增对话框
}

//编辑对话框的取消按钮点击事件
const editCancel = () => {
  obj.value = {};//清空数据
  editWinVisible.value = false;//关闭对话框
}

//编辑对话框的提交按钮点击事件
const editCommit = async () => {
  try {
    const result = await seckillGoodsApi.updateSeckillGoods(obj.value);//提交修改数据
    console.log('编辑返回结果:', result);

    // 检查返回的数据是否为HTML（表示路径错误）
    if (result && typeof result === 'string' && result.includes('<!DOCTYPE html>')) {
      ElMessage.error('API路径错误，请检查后端服务是否正常运行');
      return;
    }

    if (result && (result.code === 200 || !result.code)) {
      ElMessage.success('更新成功');
      await search();//刷新表格
      editWinVisible.value = false;//关闭编辑对话框
    } else {
      ElMessage.error(result?.message || '更新失败');
    }
  } catch (error) {
    console.error('更新失败:', error);
    ElMessage.error('更新失败: ' + (error.response?.data || error.message));
  }
}

//新增对话框的提交按钮点击事件
const addCommit = async () => {
  try {
    // 验证必填字段
    if (!obj.value.activity_id) {
      ElMessage.error('请选择活动');
      return;
    }
    if (!obj.value.goods_id) {
      ElMessage.error('请选择商品');
      return;
    }
    if (!obj.value.seckill_price) {
      ElMessage.error('请输入秒杀价格');
      return;
    }
    if (!obj.value.stock) {
      ElMessage.error('请输入秒杀库存');
      return;
    }

    // 构造发送给后端的数据
    const requestData = {
      activity_id: parseInt(obj.value.activity_id),
      goods_id: parseInt(obj.value.goods_id),
      seckill_price: parseFloat(obj.value.seckill_price),
      origin: obj.value.origin || '',
      stock: parseInt(obj.value.stock),
      status: parseInt(obj.value.status) || 0
    };

    console.log('发送的新增数据:', requestData);

    // 使用现有的API方法发送请求
    const result = await seckillGoodsApi.addSeckillGoods(requestData);

    // 检查返回结果
    if (result && (result.code === 200 || result.code === undefined)) {
      console.log('请求成功:', result);
      ElMessage.success('添加成功');
      await search();
      addWinVisible.value = false;
    } else {
      ElMessage.error(result?.msg || result?.message || '添加失败');
    }
  } catch (error) {
    console.error('请求失败:', error);
    if (error.response) {
      console.error('响应状态:', error.response.status);
      console.error('响应头:', error.response.headers);

      // 尝试获取详细的错误信息
      if (error.response.data) {
        console.error('响应数据:', error.response.data);
        if (typeof error.response.data === 'object') {
          ElMessage.error(`添加失败: ${JSON.stringify(error.response.data)}`);
        } else {
          ElMessage.error(`添加失败: ${error.response.data}`);
        }
      } else {
        ElMessage.error(`添加失败: ${error.response.status} ${error.response.statusText}`);
      }
    } else {
      ElMessage.error('网络请求失败: ' + error.message);
    }
  }
}

const handleEdit = (index, row) => {
  obj.value = lodash.clone(row);
  editWinVisible.value = true;
  console.log(index, row)
}

const handleDelete = (index, row) => {
  ElMessageBox.confirm(
      '确认删除该行数据吗?',
      '删除提示',
      {
        confirmButtonText: '删除',
        cancelButtonText: '取消',
        type: 'error',
      }
  )
      .then(async () => {
        try {
          const result = await seckillGoodsApi.deleteSeckillGoods(row.id);
          if (result && (result.code === 200 || !result.code)) {
            ElMessage.success('删除成功');
            //重新加载数据
            //设置从第一页开始查询
            searchObj.value.current = 1;
            await search();
          } else {
            ElMessage.error(result.message || '删除失败');
          }
        } catch (error) {
          ElMessage.error('删除失败: ' + error.message);
        }
      })
      .catch(() => {
      })
}

// 切换秒杀商品状态
const handleStatusChange = async (row) => {
  try {
    const result = await seckillGoodsApi.reverseStatus(row.id);
    if (result && (result.code === 200 || !result.code)) {
      ElMessage.success(result.message || '状态更新成功');
      await search(); // 刷新表格
    } else {
      ElMessage.error(result.message || '状态更新失败');
    }
  } catch (error) {
    ElMessage.error('状态更新失败: ' + error.message);
  }
}

// 格式化状态显示 (0:未开始,1:进行中,2:已售空,3:已结束)
const formatStatus = (status) => {
  switch (status) {
    case 0:
      return '未开始';
    case 1:
      return '进行中';
    case 2:
      return '已售空';
    case 3:
      return '已结束';
    default:
      return '未知状态';
  }
}

// 获取状态标签类型
const getStatusType = (status) => {
  switch (status) {
    case 0:
      return 'info';
    case 1:
      return 'success';
    case 2:
      return 'warning';
    case 3:
      return 'danger';
    default:
      return 'info';
  }
}

// 根据商品ID获取商品名称 (模仿orderAddr的getGoodsInfo返回值处理)
const getGoodsNameById = (goodsId) => {
  if (!goodsId) return '';

  const goodsInfo = goodsInfoMap.value.get(goodsId);
  return goodsInfo && goodsInfo.name ? goodsInfo.name : '';
}

// 根据活动ID获取活动名称 (模仿orderAddr的getUserInfo返回值处理)
const getActivityNameById = (activityId) => {
  if (!activityId) return '';

  const activityInfo = activityInfoMap.value.get(activityId);
  return activityInfo && activityInfo.name ? activityInfo.name : '';
}
</script>

<template>
  <div class="seckill-goods-management">
    <h2>秒杀商品管理</h2>

    <div class="tips-container">
      <el-alert
          title="请输入完整的名称，否则会查询不到"
          type="info"
          show-icon
          size="small"
          class="search-tip"
          :closable="false"
      />
    </div>

    <el-form :inline="true" :model="searchObj" class="demo-form-inline" style="margin-top:10px">
      <el-form-item label="活动名称">
        <el-input
            v-model="searchObj.activity_name"
            placeholder="请输入活动名称"
            clearable
        />
      </el-form-item>
      <el-form-item label="商品名称">
        <el-input
            v-model="searchObj.goods_name"
            placeholder="请输入商品名称"
            clearable
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handlerSearch">查询</el-button>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="resetSearch">重置</el-button>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handlerAdd">新增</el-button>
      </el-form-item>
    </el-form>

    <el-table :data="tableData" style="width: 100%">
      <el-table-column prop="id" label="秒杀商品ID"></el-table-column>
      <el-table-column prop="activity_id" label="活动名称">
        <template #default="scope">
          {{ getActivityNameById(scope.row.activity_id) }}
        </template>
      </el-table-column>
      <el-table-column prop="goods_id" label="商品名称">
        <template #default="scope">
          {{ getGoodsNameById(scope.row.goods_id) }}
        </template>
      </el-table-column>
      <el-table-column prop="seckill_price" label="秒杀价格"></el-table-column>
      <el-table-column prop="origin" label="发货地"></el-table-column>
      <el-table-column prop="stock" label="秒杀库存"></el-table-column>
      <el-table-column prop="status" label="状态">
        <template #default="scope">
          <el-tag :type="getStatusType(scope.row.status)">
            {{ formatStatus(scope.row.status) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="create_time" label="创建时间"></el-table-column>
      <el-table-column label="处理按钮">
        <template #default="scope">
          <el-button size="small" @click="handleEdit(scope.$index, scope.row)">
            编辑
          </el-button>
          <el-button
              size="small"
              :type="scope.row.status === 1 ? 'danger' : 'success'"
              @click="handleStatusChange(scope.row)"
          >
            {{ scope.row.status === 1 ? '结束' : (scope.row.status === 0 ? '启用' : (scope.row.status === 2 ? '已售空' : '启用')) }}
          </el-button>
          <el-button
              size="small"
              type="danger"
              @click="handleDelete(scope.$index, scope.row)"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination
        v-model:current-page="searchObj.current"
        v-model:page-size="searchObj.limit"
        :page-sizes="[10,20,30,50]"
        background
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
    />

    <!--编辑对话框-->
    <el-dialog v-model="editWinVisible" title="编辑秒杀商品" width="500">
      <el-form :model="obj">
        <el-form-item label="活动ID" :label-width="100">
          <el-input v-model.number="obj.activity_id" autocomplete="off"/>
        </el-form-item>
        <el-form-item label="商品ID" :label-width="100">
          <el-input v-model.number="obj.goods_id" autocomplete="off"/>
        </el-form-item>
        <el-form-item label="秒杀价格" :label-width="100">
          <el-input v-model.number="obj.seckill_price" autocomplete="off"/>
        </el-form-item>
        <el-form-item label="发货地" :label-width="100">
          <el-input v-model="obj.origin" autocomplete="off"/>
        </el-form-item>
        <el-form-item label="秒杀库存" :label-width="100">
          <el-input v-model.number="obj.stock" autocomplete="off"/>
        </el-form-item>
        <el-form-item label="状态" :label-width="100">
          <el-select v-model="obj.status" placeholder="请选择状态">
            <el-option label="未开始" :value="0"></el-option>
            <el-option label="进行中" :value="1"></el-option>
            <el-option label="已售空" :value="2"></el-option>
            <el-option label="已结束" :value="3"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="editCancel">取消</el-button>
          <el-button type="primary" @click="editCommit">
            提交
          </el-button>
        </div>
      </template>
    </el-dialog>

    <!--新增对话框-->
    <el-dialog v-model="addWinVisible" title="新增秒杀商品" width="500">
      <el-form :model="obj">
        <el-form-item label="活动" :label-width="100">
          <el-select
              v-model="obj.activity_id"
              filterable
              placeholder="请选择活动">
            <el-option
                v-for="activity in activityInfoMap"
                :key="activity[0] + ''"
                :label="activity[1] && activity[1].name ? activity[1].name : `活动-${activity[0]}`"
                :value="activity[0]">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="商品" :label-width="100">
          <el-select
              v-model="obj.goods_id"
              filterable
              placeholder="请选择商品">
            <el-option
                v-for="goods in goodsList"
                :key="goods.id"
                :label="goods.name"
                :value="goods.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="秒杀价格" :label-width="100">
          <el-input v-model.number="obj.seckill_price" autocomplete="off"/>
        </el-form-item>
        <el-form-item label="发货地" :label-width="100">
          <el-input v-model="obj.origin" autocomplete="off"/>
        </el-form-item>
        <el-form-item label="秒杀库存" :label-width="100">
          <el-input v-model.number="obj.stock" autocomplete="off"/>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="addCancel">取消</el-button>
          <el-button type="primary" @click="addCommit">
            提交
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>
.seckill-goods-management {
  padding: 20px;
  background-color: #fff;
}

.seckill-goods-management h2 {
  margin-bottom: 20px;
}

.tips-container {
  margin-bottom: 15px;
}

.search-tip {
  background-color: #f4f4f5;
  color: #909399;
  border: none;
  padding: 8px 12px;
}
</style>
